// Package rediscaptcha_store pkg/redis-captcha-store/redis_captcha_service.go
package rediscaptcha_store

import (
	"context"
	"github.com/go-redis/redis/v8"
	"github.com/mojocn/base64Captcha"
	"time"
)

// RedisCaptchaStore 基于Redis的验证码存储实现
type RedisCaptchaStore struct {
	redisClient *redis.Client
	expiration  time.Duration
	keyPrefix   string
}

// 确保RedisCaptchaStore实现了base64Captcha.Store接口
var _ base64Captcha.Store = (*RedisCaptchaStore)(nil)

// NewRedisCaptchaStore 创建基于Redis的验证码存储
func NewRedisCaptchaStore(redisClient *redis.Client, expiration time.Duration) *RedisCaptchaStore {
	return &RedisCaptchaStore{
		redisClient: redisClient,
		expiration:  expiration,
		keyPrefix:   "captcha:", // 验证码键前缀
	}
}

// Set 存储验证码到Redis
func (r *RedisCaptchaStore) Set(id string, value string) error {
	ctx := context.Background()
	key := r.keyPrefix + id
	return r.redisClient.Set(ctx, key, value, r.expiration).Err()
}

// Get 从Redis获取验证码，如果指定clear为true则获取后删除
func (r *RedisCaptchaStore) Get(id string, clear bool) string {
	ctx := context.Background()
	key := r.keyPrefix + id

	// 获取验证码
	val, err := r.redisClient.Get(ctx, key).Result()
	if err != nil {
		return ""
	}

	// 如果需要清除，则删除验证码
	if clear {
		r.redisClient.Del(ctx, key)
	}

	return val
}

// Verify 验证验证码是否正确
func (r *RedisCaptchaStore) Verify(id, answer string, clear bool) bool {
	// 获取存储的验证码
	storedValue := r.Get(id, clear)

	// 如果存储的验证码为空，则验证失败
	if storedValue == "" {
		return false
	}

	// 不区分大小写比较验证码
	return answer == storedValue
}
